﻿using AdminBase.Common.Helpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace AdminBase.Common.Attributes
{
    /// <summary>
    /// 异常处理
    /// </summary>
    public class AsyncExceptionFilterAttribute : Attribute, IAsyncExceptionFilter
    {
        private readonly ILogger<AsyncExceptionFilterAttribute> _logger;
        public AsyncExceptionFilterAttribute(ILogger<AsyncExceptionFilterAttribute> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 重写OnExceptionAsync方法，定义自己的处理逻辑，发生异常后在这里处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                _logger.LogError(context.Exception, $"发生异常：{context.Exception.Message}");
                var apiResult = ResultHelper.Error(
                    message: "服务器错误，请联系管理员",
                    statusCodes: StatusCodes.Status500InternalServerError,
                    errors: context.Exception.Message);
                context.Result = new ObjectResult(apiResult);
            }
            // 标记异常已经被处理，防止异常继续向上传播
            context.ExceptionHandled = true;
            await Task.CompletedTask;
        }
    }
}
